// +----------------------------------------------------------------------
// | JavaWeb_EleVue_Pro前后端分离旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2021 上海JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <javaweb520@gmail.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package com.javaweb.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.XmlUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.admin.entity.*;
import com.javaweb.admin.mapper.KdlPurchaseinReturnBMapper;
import com.javaweb.admin.query.KdlPurchaseinQuery;
import com.javaweb.admin.service.INcServiceLogService;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.config.DataSourceType;
import com.javaweb.common.config.SpecifyDataSource;
import com.javaweb.common.utils.CommonUtils;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.admin.constant.KdlPurchaseinReturnConstant;
import com.javaweb.admin.mapper.KdlPurchaseinReturnMapper;
import com.javaweb.admin.query.KdlPurchaseinReturnQuery;
import com.javaweb.admin.service.IKdlPurchaseinReturnService;
import com.javaweb.common.utils.StringUtils;
import com.javaweb.system.constant.Constants;
import com.javaweb.system.utils.ShiroUtils;
import com.javaweb.admin.vo.kdlpurchaseinreturn.KdlPurchaseinReturnInfoVo;
import com.javaweb.admin.vo.kdlpurchaseinreturn.KdlPurchaseinReturnListVo;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.JsonResult;
import com.seegw.shaphar.DDKJConfig;
import com.seegw.shaphar.KDLConfig;
import com.seegw.shaphar.KDLRequest;
import com.sphsine.bip.SHYPConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.Serializable;
import java.util.*;

/**
  * <p>
  * 采购退货 服务类实现
  * </p>
  *
  * @author 鲲鹏
  * @since 2024-01-26
  */
@Service
public class KdlPurchaseinReturnServiceImpl extends BaseServiceImpl<KdlPurchaseinReturnMapper, KdlPurchaseinReturn> implements IKdlPurchaseinReturnService {

    @Autowired
    private KdlPurchaseinReturnMapper kdlPurchaseinReturnMapper;

    @Autowired
    private KdlPurchaseinReturnBMapper kdlPurchaseinReturnBMapper;

    @Autowired
    INcServiceLogService ncServiceLogService;

    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getList(BaseQuery query) {
        KdlPurchaseinReturnQuery kdlPurchaseinReturnQuery = (KdlPurchaseinReturnQuery) query;
        // 查询条件
        QueryWrapper<KdlPurchaseinReturn> queryWrapper = new QueryWrapper<>();
        // queryWrapper.orderByDesc("id");

        // 获取数据列表
        IPage<KdlPurchaseinReturn> page = new Page<>(kdlPurchaseinReturnQuery.getPage(), kdlPurchaseinReturnQuery.getLimit());
        IPage<KdlPurchaseinReturn> pageData = kdlPurchaseinReturnMapper.selectPage(page, queryWrapper);
//        pageData.convert(x -> {
//            KdlPurchaseinReturnListVo kdlPurchaseinReturnListVo = Convert.convert(KdlPurchaseinReturnListVo.class, x);
//            return kdlPurchaseinReturnListVo;
//        });
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getPurchaseinReturnList(BaseQuery query) {
        KdlPurchaseinReturnQuery kdlPurchaseinQuery = (KdlPurchaseinReturnQuery) query;
        // 获取数据列表
        kdlPurchaseinQuery.setOrglist(ShiroUtils.getOrgCode());
        IPage<KdlPurchaseinReturn> page = new Page<>(kdlPurchaseinQuery.getPage(), kdlPurchaseinQuery.getLimit());
        IPage<KdlPurchaseinReturn> pageData = kdlPurchaseinReturnMapper.getPurchaseinReturnList(page, kdlPurchaseinQuery);
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getPurchaseinReturnDetail(Integer pid) {
        return JsonResult.success(kdlPurchaseinReturnMapper.getPurchaseinReturnDetail(pid));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public List<KdlPurchaseinReturn> getPurchaseReturnSubmitList() {
        return kdlPurchaseinReturnMapper.getPurchaseReturnSubmitList();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String getMaxSyncTime() {
        return kdlPurchaseinReturnMapper.GetMaxSyncTime();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncPurchaseReturn(KdlPurchaseinReturnQuery query) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + query.getPrincipalid() + "</PrincipalID>");
            sb.append("<DocType>" + query.getDoctype() + "</DocType>");
            sb.append("<StartTime>" + kdlPurchaseinReturnMapper.GetMaxSyncTime() + "</StartTime>");
            sb.append("<EndTime>" + query.getEndtime() + "</EndTime>");
            sb.append("</Head>");
            sb.append("</CAH3PL>");
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = sb.toString();
            log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST: SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    log.setResponseBody(result);
                    log.setResponseCode(resCode);
                    log.setResponseResult(resRemark);
                    ncServiceLogService.save(log);
                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlPurchaseinDto dto = new KdlPurchaseinDto();
                        KdlPurchaseinReturn purchasein = new KdlPurchaseinReturn();
                        KdlPurchaseinReturnB purchaseinB = new KdlPurchaseinReturnB();
                        purchasein.setPrincipalid(CommonUtils.XmlGetNodeContent(headResult, "PrincipalID"));
                        purchasein.setPrincipalname(CommonUtils.XmlGetNodeContent(headResult, "PrincipalName"));
                        purchasein.setVendorpo(CommonUtils.XmlGetNodeContent(headResult, "VendorPO"));
                        purchasein.setDoctype(CommonUtils.XmlGetNodeContent(headResult, "DocType"));
                        purchasein.setCustomername(CommonUtils.XmlGetNodeContent(headResult, "CustomerName"));
                        purchasein.setDeliveryaddress(CommonUtils.XmlGetNodeContent(headResult, "DeliveryAddress"));
                        purchasein.setPlantaddress(CommonUtils.XmlGetNodeContent(headResult, "PlantAddress"));
                        purchasein.setCompanycode(CommonUtils.XmlGetNodeContent(headResult, "CompanyCode"));


                        String pgidate = DateUtil.format(DateUtil.parse(CommonUtils.XmlGetNodeContent(headResult, "PGIDate"), DateUtils.YYYYMMDD), DateUtils.YYYY_MM_DD);
                        purchasein.setPgidate(pgidate);
                        purchasein.setPgiid(CommonUtils.XmlGetNodeContent(headResult, "PGIID"));
                        purchasein.setPgiidname(CommonUtils.XmlGetNodeContent(headResult, "PGIIDName"));
                        purchasein.setRemark(CommonUtils.XmlGetNodeContent(headResult, "Remark"));
                        List<KdlPurchaseinReturn> list = kdlPurchaseinReturnMapper.selectList(new QueryWrapper<KdlPurchaseinReturn>().eq("vendorpo", purchasein.getVendorpo()));
                        if (list.size() == 0) {
                            kdlPurchaseinReturnMapper.insert(purchasein);
                        } else {
                            purchasein.setUpdateTime(DateUtils.now());
                            kdlPurchaseinReturnMapper.update(purchasein, new UpdateWrapper<KdlPurchaseinReturn>().eq("vendorpo", purchasein.getVendorpo()));
                        }
                        //遍历明细Details
                        Element detail = null;
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            detail = (Element) detailResult.getChildNodes().item(i);
                            purchaseinB.setPid(purchasein.getId());
                            purchaseinB.setVendorpolineno(CommonUtils.XmlGetNodeContent(detail, "VendorPOLineNo"));
                            purchaseinB.setCahdnno(CommonUtils.XmlGetNodeContent(detail, "CAHDNNO"));
                            purchaseinB.setCahlineno(CommonUtils.XmlGetNodeContent(detail, "CAHLineNo"));
                            purchaseinB.setMaterialcode(CommonUtils.XmlGetNodeContent(detail, "MaterialCode"));
                            purchaseinB.setCahmaterialcode(CommonUtils.XmlGetNodeContent(detail, "CAHMaterialCode"));
                            purchaseinB.setMaterialdes(CommonUtils.XmlGetNodeContent(detail, "MaterialDes"));
                            purchaseinB.setComdescription(CommonUtils.XmlGetNodeContent(detail, "ComDescription"));
                            purchaseinB.setMaterialspec(CommonUtils.XmlGetNodeContent(detail, "MaterialSpec"));
                            purchaseinB.setMaterialform(CommonUtils.XmlGetNodeContent(detail, "MaterialForm"));
                            purchaseinB.setRegistno(CommonUtils.XmlGetNodeContent(detail, "RegistNo"));
                            purchaseinB.setManufacturername(CommonUtils.XmlGetNodeContent(detail, "ManufacturerName"));
                            purchaseinB.setSubmaufacturername(CommonUtils.XmlGetNodeContent(detail, "SubMaufacturerName"));
                            purchaseinB.setVendorissueplant(CommonUtils.XmlGetNodeContent(detail, "VendorIssuePlant"));
                            purchaseinB.setCahissueplant(CommonUtils.XmlGetNodeContent(detail, "CAHIssuePlant"));
                            purchaseinB.setPgiquantity(CommonUtils.XmlGetNodeContent(detail, "PGIQuantity", 0));
                            purchaseinB.setPgiitemfinish(CommonUtils.XmlGetNodeContent(detail, "PGIItemFinish"));
                            purchaseinB.setCahuom(CommonUtils.XmlGetNodeContent(detail, "CAHUOM"));
                            purchaseinB.setVendoruom(CommonUtils.XmlGetNodeContent(detail, "VendorUOM"));
                            purchaseinB.setVendorbatch(CommonUtils.XmlGetNodeContent(detail, "VendorBatch"));
                            purchaseinB.setSerialno(CommonUtils.XmlGetNodeContent(detail, "SerialNo"));
                            purchaseinB.setExpireddate(CommonUtils.XmlGetNodeContent(detail, "ExpiredDate"));
                            purchaseinB.setManufacturedate(CommonUtils.XmlGetNodeContent(detail, "ManufactureDate"));
                            purchaseinB.setCahlocation(CommonUtils.XmlGetNodeContent(detail, "CAHLocation"));
                            purchaseinB.setBoxno(CommonUtils.XmlGetNodeContent(detail, "BoxNo"));
                            purchaseinB.setBoxflag(CommonUtils.XmlGetNodeContent(detail, "BoxFlag"));
                            purchaseinB.setSyncTime(CommonUtils.XmlGetNodeContent(detail, "Time"));
                            purchaseinB.setSapbatch(CommonUtils.XmlGetNodeContent(detail, "SAPbatch"));

                            List<KdlPurchaseinReturnB> list1 = kdlPurchaseinReturnBMapper.selectList(new QueryWrapper<KdlPurchaseinReturnB>().eq("vendorpolineno", purchaseinB.getVendorpolineno()).eq("cahlineno",purchaseinB.getCahlineno()));
                            if (list1.size() == 0)  {
                                if(!StringUtils.isNull(purchasein.getId())) {
                                    purchaseinB.setStatus(Constants.NC_TO_SUBMIT_STATUS);
                                    kdlPurchaseinReturnBMapper.insert(purchaseinB);
                                }
                            } else {
                                if(!list1.get(0).getStatus().equals(Constants.NC_SUBMIT_STATUS)) {
                                    purchaseinB.setStatus(list1.get(0).getStatus());
                                    purchaseinB.setUpdateTime(DateUtils.now());
                                    purchaseinB.setId(list1.get(0).getId());
                                    kdlPurchaseinReturnBMapper.updateById(purchaseinB);
                                }
                            }
                        }

                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    /**
     * 获取详情Vo
     *
     * @param id 记录ID
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public Object getInfo(Serializable id) {
        KdlPurchaseinReturn entity = (KdlPurchaseinReturn) super.getInfo(id);
        // 返回视图Vo
        KdlPurchaseinReturnInfoVo kdlPurchaseinReturnInfoVo = new KdlPurchaseinReturnInfoVo();
        // 拷贝属性
        BeanUtils.copyProperties(entity, kdlPurchaseinReturnInfoVo);
        return kdlPurchaseinReturnInfoVo;
    }

    /**
     * 添加、更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult edit(KdlPurchaseinReturn entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
        } else {
        }
        return super.edit(entity);
    }

    /**
     * 删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult delete(KdlPurchaseinReturn entity) {
        entity.setMark(0);
        return super.delete(entity);
    }

}